<template>
  <Form
    class="custom-ivu-form"
    ref="formRef"
    style="width: 90%"
    :label-width="120"
    :model="formData"
    :rules="rules"
    @submit.native.prevent="handleFormSubmit"
  >
    <FormItem label="供稿单位" prop="name">
      <Input v-model="formData.name" placeholder="请输入供稿单位" size="large" clearable :maxlength="15"></Input>
    </FormItem>

    <FormItem label="供稿额度" prop="produceNum">
      <InputNumber
        v-model="formData.produceNum"
        size="large"
        style="width: 100%"
        placeholder="请输入供稿 额度"
        :min="0"
        :precision="0"
        @input="handleInput"
      ></InputNumber>
    </FormItem>

    <FormItem label="配置日期" style="margin-bottom: 0">
      <div class="f14" style="line-height: 36px">
        {{ new Date() | dateFormat('yyyy年MM月DD日') }}
      </div>
    </FormItem>

    <Button class="d-none" type="primary" html-type="submit">查询</Button>
  </Form>
</template>

<script>
const validator = (rule, value, callback) => {
  const num = Number(value)
  if (value == null || (num !== 0 && String(value).trim() === '')) {
    callback(new Error('供稿额度不能为空'))
  } else if (Number.isNaN(num)) {
    callback(new Error('错误的输入'))
  } else if (num < 0) {
    callback(new Error('供稿额度不能小于0'))
  } else if (String(num).length > 10) {
    callback(new Error('供稿额度不能超过10位数字'))
  } else {
    callback()
  }
}
const createRules = () => ({
  name: { required: true, message: '供稿单位不能为空', trigger: 'blur' },
  produceNum: { required: true, validator, trigger: 'blur' },
})

export default {
  name: 'ProvideUnitForm',

  props: {
    formData: {
      type: Object,
      default() {
        return {}
      },
    },

    disabledList: {
      type: Object,
      default() {
        return {}
      },
    },
  },

  data() {
    return {
      rules: createRules(),
    }
  },

  methods: {
    handleFormSubmit() {
      this.$refs.formRef.validate().then((valid) => {
        // console.log('valid', valid)
        // return
        if (!valid) return
        this.formData.produceNum = Number(this.formData.produceNum)
        const data = { ...this.formData }
        this.$emit('on-theme-submit', data)
      })
    },

    handleInput() {
      // 限制不为负数
      if (Number(this.formData.produceNum) < 0) {
        this.formData.produceNum = 0
        return
      }
      // 限制长度
      const maxLength = 10 // 设定最大长度
      const str = String(this.formData.produceNum)
      let res = ''
      if (str.length > maxLength) {
        res = str.slice(0, maxLength) // 截断超过长度的部分
        this.$nextTick(() => {
          this.formData.produceNum = Number(res)
        })
      }
    },

    parser(n) {
      if (Number(n) < 0) return '0'
      if (n.length > 10) return n.slice(0, 10)
      return n
    },
  },
}
</script>

<style lang="less" scoped></style>
